<template>
  <div class="my-item-detail-container">
    <!-- 顶部导航 -->
    <div class="header-bar">
      <div class="header-left" @click="router.back()">
        <i class="fas fa-arrow-left"></i>
      </div>
      <div class="header-title">物品详情</div>
      <div class="header-right" v-if="isOwner">
        <el-dropdown @command="handleMoreCommand">
          <span class="el-dropdown-link">
            <i class="fas fa-ellipsis-v"></i>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="edit">编辑物品</el-dropdown-item>
              <el-dropdown-item
                  :command="itemData.status === 1 ? 'offline' : 'relist'"
              >
                {{ itemData.status === 1 ? '下架物品' : '重新上架' }}
              </el-dropdown-item>
              <el-dropdown-item v-if="itemData.status !== 1" command="delete" divided>
                删除物品
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 状态指示器 -->
    <div class="status-indicator" :class="statusClass">
      <i :class="statusIcon"></i>
      <span>{{ statusText }}</span>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 轮播图 -->
      <div class="image-carousel" v-if="itemData.images && itemData.images.length">
        <van-swipe class="carousel" :autoplay="3000" indicator-color="white">
          <van-swipe-item v-for="(image, index) in itemData.images" :key="index">
            <el-image :src="image" class="carousel-image"></el-image>
          </van-swipe-item>
        </van-swipe>
      </div>

      <!-- 商品信息 -->
      <div class="item-info">
        <h2 class="item-title">{{ itemData.title }}</h2>

        <div class="meta-info">
          <span class="price">¥{{ itemData.price }}</span>
          <span class="price-unit">{{ priceSuffix }}</span>
          <span class="views">
            <i class="fas fa-eye"></i> {{ itemData.viewCount || 0 }}
          </span>
        </div>

        <div class="tags" v-if="itemData.tags && itemData.tags.length">
          <span class="tag" v-for="(tag, index) in itemData.tags" :key="index">
            {{ tag }}
          </span>
        </div>

        <div class="description">
          <h3>物品描述</h3>
          <p>{{ itemData.description || '暂无描述' }}</p>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 - 根据状态显示不同按钮 -->
    <div class="action-bar" v-if="isOwner">
      <template v-if="itemData.status === 1">
        <!-- 上架状态的操作按钮 -->
        <el-button type="warning" @click="handleOffline">下架物品</el-button>
        <el-button type="primary" @click="handleEdit">编辑物品</el-button>
      </template>
      <template v-else>
        <!-- 下架状态的操作按钮 -->
        <el-button type="success" @click="handleRelist">重新上架</el-button>
        <el-button type="primary" @click="handleEdit">编辑物品</el-button>
        <el-button type="danger" @click="handleDelete">删除物品</el-button>
      </template>
    </div>

    <!-- 非所有者看到的操作栏 -->
    <div class="action-bar" v-else>
      <el-button type="primary" icon="fas fa-comment">联系卖家</el-button>
      <el-button type="danger" icon="fas fa-shopping-cart">立即购买</el-button>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑物品信息"
        width="90%"
    >
      <!-- 编辑表单内容 -->
      <div class="edit-form">
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="物品名称">
            <el-input v-model="editForm.title" />
          </el-form-item>
          <el-form-item label="物品描述">
            <el-input v-model="editForm.description" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input-number v-model="editForm.price" :min="0" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 自定义确认对话框 -->
    <div v-if="customDialog.visible" class="custom-dialog-overlay">
      <div class="custom-dialog">
        <div class="custom-dialog-header">
          <h3>{{ customDialog.title }}</h3>
        </div>
        <div class="custom-dialog-body">
          <p>{{ customDialog.message }}</p>
        </div>
        <div class="custom-dialog-footer">
          <el-button @click="customDialog.visible = false">取消</el-button>
          <el-button
              :type="customDialog.type"
              @click="customDialog.confirm"
          >
            确定
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from "@/utils/axios.ts";
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 物品数据
const itemData = reactive({
  itemId: null,
  title: '',
  description: '',
  price: 0,
  images: [],
  tags: [],
  viewCount: 0,
  status: 1, // 1:上架, 2:下架
  type: 1, // 1:出售, 2:出租
  rentType: 1,
  rentCount: 1
})

// 编辑对话框
const editDialogVisible = ref(false)
const editForm = reactive({
  title: '',
  description: '',
  price: 0
})

// 自定义对话框数据
const customDialog = reactive({
  visible: false,
  title: '',
  message: '',
  type: 'primary',
  confirm: () => {}
})

// 计算属性
const isOwner = computed(() => {
  // 这里需要根据实际业务逻辑判断当前用户是否是物品所有者
  // 假设从我的发布进入的都是所有者
  return true
})

const statusClass = computed(() => {
  return itemData.status === 1 ? 'status-on' : 'status-off'
})

const statusIcon = computed(() => {
  return itemData.status === 1 ? 'fas fa-check-circle' : 'fas fa-pause-circle'
})

const statusText = computed(() => {
  return itemData.status === 1 ? '已上架' : '已下架'
})

const priceSuffix = computed(() => {
  if (itemData.type === 1) return '出售'

  const rentTypeMap = {
    1: '天',
    2: '周',
    3: '月'
  }
  return `/${itemData.rentCount}${rentTypeMap[itemData.rentType]} 出租`
})

// 生命周期
onMounted(() => {
  // 从路由参数获取物品ID和状态
  const itemId = route.params.id
  const status = route.query.status || 1

  // 设置初始状态
  itemData.status = parseInt(status)

  // 获取物品详情
  fetchItemDetail(itemId)
})

// 方法
const fetchItemDetail = async (itemId) => {
  try {
    console.log("获取物品详情，ID:", itemId)
    const response = await axios.post("/api/userItems/getById?id=" + itemId)
    console.log("API响应:", response)

    // 更新物品数据
    Object.assign(itemData, response)

    // 处理图片数据 - 确保是数组格式
    if (response?.images || response.images) {
      const imagesData = response.images
      console.log("imagesData:",imagesData)
      if (typeof imagesData === 'string') {
        try {
          itemData.images = JSON.parse(imagesData)
        } catch (error) {
          console.error('解析图片数据失败:', error)
          itemData.images = []
        }
      } else if (Array.isArray(imagesData)) {
        itemData.images = imagesData
      } else {
        itemData.images = []
      }
    } else {
      itemData.images = []
    }

    // 处理标签数据 - 确保是数组格式
    if (response?.tag || response.tag) {
      const tagsData = response?.tag || response.tag
      console.log("tag数据", response.tag)
      if (typeof tagsData === 'string') {
        try {
          itemData.tags = JSON.parse(tagsData)
        } catch (error) {
          console.error('解析标签数据失败:', error)
          itemData.tags = []
        }
      } else if (Array.isArray(tagsData)) {
        itemData.tags = tagsData
      } else {
        itemData.tags = []
      }
    } else {
      itemData.tags = []
    }

    console.log("处理后的物品数据:", itemData)
  } catch (error) {
    console.error('获取物品详情失败:', error)
    ElMessage.error('获取物品详情失败')
  }
}

const handleMoreCommand = (command) => {
  switch (command) {
    case 'edit':
      handleEdit()
      break
    case 'offline':
      handleOffline()
      break
    case 'relist':
      handleRelist()
      break
    case 'delete':
      handleDelete()
      break
  }
}

const handleEdit = () => {
  // 填充编辑表单
  editForm.title = itemData.title
  editForm.description = itemData.description
  editForm.price = itemData.price

  editDialogVisible.value = true
}

const saveEdit = async () => {
  try {
    // 调用API保存编辑
    const response = await axios.post('/api/userItems/editItem', {
      itemId: itemData.itemId,
      title: editForm.title,
      description: editForm.description,
      price: editForm.price
    })

    if (response.code === 200) {
      ElMessage.success('保存成功')
      editDialogVisible.value = false

      // 更新本地数据
      itemData.title = editForm.title
      itemData.description = editForm.description
      itemData.price = editForm.price
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

const handleOffline = async () => {
  customDialog.title = '下架确认'
  customDialog.message = '确定要下架这个物品吗?'
  customDialog.type = 'warning'
  customDialog.confirm = async () => {
    try {
      const response = await axios.post(`/api/userItems/changeStatus/down/${itemData.itemId}/${itemData.status}`)
      if (response.code === 200) {
        ElMessage.success('已下架')
        itemData.status = 2
      }
      customDialog.visible = false
    } catch (error) {
      console.error('下架失败:', error)
      customDialog.visible = false
    }
  }
  customDialog.visible = true
}

const handleRelist = async () => {
  customDialog.title = '重新上架确认'
  customDialog.message = '确定要重新上架这个物品吗?'
  customDialog.type = 'success'
  customDialog.confirm = async () => {
    try {
      const response = await axios.post(`/api/userItems/changeStatus/up/${itemData.itemId}/${itemData.status}`)
      if (response.code === 200) {
        ElMessage.success('已重新上架')
        itemData.status = 1
      }
      customDialog.visible = false
    } catch (error) {
      console.error('重新上架失败:', error)
      customDialog.visible = false
    }
  }
  customDialog.visible = true
}

const handleDelete = async () => {
  customDialog.title = '删除确认'
  customDialog.message = '确定要删除这个物品吗?此操作不可恢复'
  customDialog.type = 'danger'
  customDialog.confirm = async () => {
    try {
      const response = await axios.post(`/api/userItems/deleteById/${itemData.itemId}`)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        router.back()
      }
      customDialog.visible = false
    } catch (error) {
      console.error('删除失败:', error)
      customDialog.visible = false
    }
  }
  customDialog.visible = true
}
</script>

<style scoped>
.my-item-detail-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 70px;
}

.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-title {
  font-weight: bold;
  font-size: 18px;
}

.status-indicator {
  padding: 8px 15px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.status-indicator i {
  margin-right: 5px;
}

.status-on {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-off {
  background-color: #f5f5f5;
  color: #9e9e9e;
}

.content-area {
  padding: 15px;
}

.image-carousel {
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 15px;
}

.carousel {
  height: 300px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  background: white;
  border-radius: 12px;
  padding: 15px;
}

.item-title {
  font-size: 18px;
  margin-bottom: 10px;
}

.meta-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.price {
  font-size: 24px;
  font-weight: bold;
  color: #ff4444;
  margin-right: 5px;
}

.price-unit {
  color: #666;
  margin-right: 15px;
}

.views {
  color: #999;
}

.tags {
  margin-bottom: 15px;
}

.tag {
  display: inline-block;
  padding: 4px 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  margin-right: 8px;
  font-size: 12px;
  color: #666;
}

.description h3 {
  margin-bottom: 8px;
  font-size: 16px;
}

.description p {
  color: #666;
  line-height: 1.6;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 15px;
  background: white;
  display: flex;
  gap: 10px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.action-bar .el-button {
  flex: 1;
}

/* 自定义对话框样式 */
.custom-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.custom-dialog {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 80%;
  max-width: 400px;
  overflow: hidden;
  animation: dialog-fade-in 0.3s;
}

@keyframes dialog-fade-in {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.custom-dialog-header {
  padding: 20px 20px 10px;
  text-align: center;
  border-bottom: 1px solid #eee;
}

.custom-dialog-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.custom-dialog-body {
  padding: 20px;
  text-align: center;
  color: #666;
  font-size: 16px;
  line-height: 1.5;
}

.custom-dialog-footer {
  padding: 15px 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
  border-top: 1px solid #eee;
}

.custom-dialog-footer .el-button {
  min-width: 80px;
  border-radius: 6px;
}
</style>